#!/usr/bin/env python
#coding=utf-8

"""
getinfo.py
Created by Luke on 2009-04-29.
Copyright (c) 2009 Alibaba. All rights reserved.
"""

import urllib
from xml2dict import XML2Dict
import codecs


def gbk2utf8(xml):
	return xml.decode("gbk").encode("utf8").replace('gbk', 'utf-8');

def get_ip_info(ip):
	url="http://www.yodao.com/smartresult-xml/search.s?type=ip&q=%s"%ip
	return  gbk2utf8(urllib.urlopen(url).read())

def get_mobile_info(mobile):
	url="http://www.yodao.com/smartresult-xml/search.s?type=mobile&q=%s"%mobile
	return gbk2utf8(urllib.urlopen(url).read())
	

def main():
	fr = open('x.csv')
	wr = codecs.open('y.csv','w','gbk')
	xml = XML2Dict()
	for line in fr.readlines():
		line = line.rstrip('\n')
		items = line.split(',')
		ip_item = items[2]
		mobile_item = items[3]
		ip_dict = xml.fromstring(get_ip_info(ip_item))
		mobile_dict = xml.fromstring(get_mobile_info(mobile_item))
		new_line=''
		if ip_dict.smartresult!=None:
			new_line = items[0]+','+items[1]+','+items[2]+','+ip_dict.smartresult.product.location.encode("gbk")
		else:
			new_line = items[0]+','+items[1]+','+items[2]+','
		if mobile_dict.smartresult!=None:
			new_line = new_line+','+items[3]+','+mobile_dict.smartresult.product.location.encode("gbk")+'\n'
		else:
			new_line = new_line+','+items[3]+','+'\n'
		print new_line.decode("gbk")
		wr.write(new_line.decode("gbk"))
	fr.close();
	wr.close();


if __name__ == '__main__':
	main()

